package com.lh0811.forge.pserv.uacs.server.config.auth.phone_pwd;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.lh0811.forge.dependency.basic_code.encrypt.PwdUtil;
import com.lh0811.forge.dependency.basic_web.exception.CommonException;
import com.lh0811.forge.dependency.basic_web.response.ServerResponse;
import com.lh0811.forge.dependency.security.core.api.authentication.SecurityVoucherVerification;
import com.lh0811.forge.dependency.security.core.model.entity.SecurityAuthority;
import com.lh0811.forge.pserv.uacs.api.param.PhonePasswordVerificationParam;
import com.lh0811.forge.pserv.uacs.server.config.auth.VerificationHandler;
import com.lh0811.forge.pserv.uacs.server.repository.dao.UacsPlateUserDao;
import com.lh0811.forge.pserv.uacs.server.repository.entity.UacsPlateUser;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class PhonePasswordVerificationAdapter implements SecurityVoucherVerification<PhonePasswordVerification> {
    @Resource
    private UacsPlateUserDao uacsPlateUserDao;

    @Resource
    private VerificationHandler verificationHandler;

    @Override
    public SecurityAuthority verification(PhonePasswordVerification verification) throws Exception {
        log.info("开始执行 PhonePasswordVerificationAdapter.{},参数:{}", "verification", JSONObject.toJSONString(verification));
        return verificationByPhoneAndPwd(new PhonePasswordVerificationParam(verification.getPhone(), verification.getPassword()));
    }

    private SecurityAuthority verificationByPhoneAndPwd(PhonePasswordVerificationParam param) throws Exception {
        log.info("开始 通过用户名密码 获取用户信息 并组装权限信息:{}", JSON.toJSONString(param));
        UacsPlateUser uacsPlateUser = uacsPlateUserDao.lambdaQuery()
                .eq(UacsPlateUser::getPhone, param.getPhone())
                .one();
        if (ObjectUtils.isEmpty(uacsPlateUser)) {
            throw CommonException.create(ServerResponse.createByError("用户名不存在"));
        }
        if (BooleanUtils.isNotTrue(uacsPlateUser.getActiveFlag())) {
            throw CommonException.create(ServerResponse.createByError("用户未激活,请联系管理员"));
        }
        if (BooleanUtils.isTrue(uacsPlateUser.getWriteOffFlag())) {
            throw CommonException.create(ServerResponse.createByError("用户已注销"));
        }
        if (!StringUtils.equals(uacsPlateUser.getPassword(), PwdUtil.hashPassword(param.getPassword(), uacsPlateUser.getSalt()))) {
            throw CommonException.create(ServerResponse.createByError("用户名与密码不匹配"));
        }
        // 构建登录后用户授权信息
        return verificationHandler.genSecurityAuthority(uacsPlateUser);
    }


}
